package com.nercel.dsj.gksales.service.impl;

import com.nercel.dsj.gksales.dao.mapper.PermissionMapper;
import com.nercel.dsj.gksales.model.QueryParams;
import com.nercel.dsj.gksales.model.RequestMapping;
import com.nercel.dsj.gksales.model.entity.Permission;
import com.nercel.dsj.gksales.service.PermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sunlin
 * @date 2018-11-16
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PermissionServiceImpl implements PermissionService {

    private final PermissionMapper permissionMapper;

    @Override
    public void save(Permission permission) {
        permissionMapper.insertSelective(permission);
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public Permission findById(Integer integer) {
        return permissionMapper.selectByPrimaryKey(integer);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.query(new QueryParams());
    }

    @Override
    public void delete(Integer integer) {
        permissionMapper.deleteByPrimaryKey(integer);
    }

    @Override
    public List<Permission> list(QueryParams queryParams) {
        return permissionMapper.query(queryParams);
    }

    @Override
    public List<RequestMapping> getNoPermissionRequestMapping(List<RequestMapping> requestMappings) {
        List<Permission> permissions = list(new QueryParams());
        List<RequestMapping> result = new ArrayList<>();
        requestMappings.forEach(requestMapping ->{
            boolean inList = false;
            for(Permission permission : permissions){
                if(permission.getUrl().equals(requestMapping.getPatternUrl())
						|| permission.getUrl().equals(requestMapping.getPatternUrl().replaceAll("^.*?:",""))){
                    inList = true;
                    break;
                }
            }
            if(!inList){
                result.add(requestMapping);
            }
        });
        return result;
    }

}
